<?php
class Model_CategoryMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Model_DbTable_Category');
        }
        return $this->_dbTable;
    }

    public function save(Model_Category $category)
    {
        $data = array(
			'id'	=> $category -> getId(),
            'name'   => $category->getName(),
            'id_parent' => $category->getIdParent(),
        );

        if (null === ($id = $category->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id, Model_Category $category)
    {
        $result = $this->getDbTable()->find($id);
        Zend_Debug::dump("ok");
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $category->setId($row->id)
                  ->setName($row->name)
                  ->setIdParent($row->id_parent);
    }
	
	public function findByIdParent($id_parent)
    {
        $table 		= $this->getDbTable();
    	$resultSet 	= $table->fetchAll(
  								$table	->select()
        								->where('id_parent = :id')
								        ->bind(array(':id'=>$id_parent))
		);
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Model_Category();
            $entry->setId($row->id)
                  ->setName($row->name)
                  ->setIdParent($row->id_parent)
                  ->setMapper($this);
            $entries[] = $entry;
        }
        return $entries;
    }
	public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Model_Category();
            $entry->setId($row->id)
                  ->setName($row->name)
                  ->setIdParent($row->id_parent)
                  ->setMapper($this);
            $entries[] = $entry;
        }
        return $entries;
    }
}
